package com.moneywelcome.orderassembly.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.moneywelcome.exceptions.MwcArgsException;
import com.moneywelcome.orderassembly.model.FinancialShares;
import com.moneywelcome.orderassembly.model.InvestRecord;
import com.moneywelcome.orderassembly.mapper.InvestRecordMapper;
import com.moneywelcome.orderassembly.service.InvestRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.moneywelcome.orderassembly.service.UserFinancialService;
import com.moneywelcome.orderassembly.util.GoldUtil;
import com.moneywelcome.orderfacade.dto.SubscribeOrderDto;
import com.moneywelcome.orderfacade.vo.InvestRecordVo;
import com.moneywelcome.orderfacade.vo.OrderPageVo;
import com.moneywelcome.orderfacade.vo.UserFinancialVo;
import com.moneywelcome.results.PageResult;
import com.moneywelcome.results.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;


/**
 * <p>
 * 申购记录表 服务实现类
 * </p>
 *
 * @author alice
 * @since 2022-01-06
 */
@Service
public class InvestRecordServiceImpl extends ServiceImpl<InvestRecordMapper, InvestRecord> implements InvestRecordService {
    @Autowired
    private UserFinancialService ufs;
    @Autowired
    private FinancialSharesServiceImpl fss;
    /*
    investRecordVo:申购订单参数对象
     */
    @Override
    public SubscribeOrderDto create(InvestRecordVo investRecordVo) {
        InvestRecord investRecord = BeanUtil.copyProperties(investRecordVo, InvestRecord.class);
        investRecord.setBuyRecordStatus(0);
        investRecord.setBuyTime(DateUtil.now());
        //生产交易编号
        investRecord.setInvestSerial(UUID.randomUUID().toString());
        if (!save(investRecord)) throw new MwcArgsException("申购记录生成失败", StatusCode.Error);
        return BeanUtil.copyProperties(investRecord, SubscribeOrderDto.class);
    }

    @Override
    public void complete() throws IOException {
        HashMap<Integer, Double> map = new HashMap<>();
        Double buyPrice=0.0;
        //获取所有待完成的记录
        List<InvestRecord> records= list(new QueryWrapper<InvestRecord>().eq("buy_record_status", 0));
        if(null==records||records.size()==0) throw new MwcArgsException("申购记录不存在",StatusCode.Error);
        for (InvestRecord record : records) {
            if(map.containsKey(record.getGoldId())){//获取黄金实时价格
                buyPrice=map.get(record.getGoldId());
            }else {
                System.out.println(record);
                buyPrice = GoldUtil.getCurrentPrice(String.valueOf(record.getGoldId())).getLastPrice();
                map.put(record.getGoldId(),buyPrice);
            }
            record.setBuyRecordStatus(1);//完成订单
            record.setCompleteTime(DateUtil.now());
            Double charge = record.getBuyCharge() * (1 - record.getBuyRate());//实际购买额
            record.setBuyPrice(buyPrice);
            record.setBuyShares(NumberUtil.round(charge / buyPrice, 2).doubleValue());
            //如果第一次购买则生成持仓记录
            if(null==record.getFinancialId()) {
                System.out.println("生成持仓记录");
                long financialId = IdUtil.getSnowflake().nextId();
                record.setFinancialId(financialId);
                UserFinancialVo userFinancialVo = new UserFinancialVo();
                userFinancialVo.setManageRate(record.getManageRate());
                userFinancialVo.setFinancialId(financialId);
                userFinancialVo.setUserId(record.getUserId());
                userFinancialVo.setGoldId(record.getGoldId());
                userFinancialVo.setVariety(record.getVariety());
                userFinancialVo.setFinancialShares(record.getBuyShares());
                ufs.create(userFinancialVo);
            }
            //生成持仓份额记录
            FinancialShares financialShares = new FinancialShares();
            financialShares.setFinancialId(record.getFinancialId());
            financialShares.setFinancialShares(record.getBuyShares());
            financialShares.setFinancialTime(DateUtil.now());
            fss.save(financialShares);
            //持仓份额更新
            ufs.updateShares(record.getFinancialId(), record.getBuyShares());
        }
        if (!saveOrUpdateBatch(records)) throw new MwcArgsException("申购失败", StatusCode.Error);
    }
    /*
    申购记录分页
     */
    @Override
    public PageResult<SubscribeOrderDto> queryRecord(OrderPageVo op) {
        QueryWrapper<InvestRecord> qw = new QueryWrapper<>();
//        if (null == op.getUserId()) throw new MwcArgsException("用户id不能为空", StatusCode.Error);
        if (null != op.getUserId())  qw.eq("user_id", op.getUserId());
        if (null!=op.getFinancialId()) qw.eq("financial_id",op.getFinancialId());
        if (null != op.getStartTime()) qw.ge("buy_time", op.getStartTime());
        if (null != op.getEndTime()) qw.le("buy_time", op.getEndTime());
        String keyword = op.getKeyword();
        if (!StrUtil.hasEmpty(keyword)) {
            qw.and(qwt -> {
                qwt.like("variety", keyword).or()
                        .like("invest_serial", keyword);
            });
        }
        Page<InvestRecord> page = page(new Page<>(op.getCurrent(), op.getSize()), qw);
        PageResult pageResult = BeanUtil.copyProperties(page, PageResult.class);
        pageResult.setData(BeanUtil.copyToList(page.getRecords(), SubscribeOrderDto.class));
        pageResult.setTotalCount(page.getTotal());
        return pageResult;
    }
}
